package com.wxy.netty.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.Scanner;

/**
 * @author 47868
 */
public class 处理关闭 {
    public static void main(String[] args) throws InterruptedException {
        //解决输入bye客户端不结束问题
        EventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) {
                        nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect("127.0.0.1", 8888);
        Channel channel = channelFuture.sync().channel();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Scanner scanner = new Scanner(System.in);
                while(true){
                    String line = scanner.nextLine();
                    if(line.equals("bye")){
                        channel.close();   //close方法是异步非阻塞的方法 不能再其之后进行关闭操作
                        break;
                    }
                    channel.writeAndFlush(line);
                }
            }
        },"input").start();

        /*//关闭连接  同步处理
        ChannelFuture closefuture = channel.closeFuture();
        closefuture.sync();
        System.out.println(Thread.currentThread().getName()+" channel已经关闭,请继续下面的操作");
        group.shutdownGracefully();*/

        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener((ChannelFutureListener) channelFuture1 -> {
            System.out.println(Thread.currentThread().getName()+" channel已经关闭,请继续下面的操作");
            group.shutdownGracefully();
        });
    }
}
